package gazzera.utils;

import java.io.*;
import java.net.*;

import net.sbbi.upnp.impls.*;
import net.sbbi.upnp.messages.*;

public class UpnpUtils
{

	private int port;
	private InternetGatewayDevice testIGD = null;
	
	
	
	public UpnpUtils(int port)
	{
		this.port = port;
	}
	public boolean find()
	{
		 int discoveryTimeout = 5000; // 5 secs to receive a response from devices
	      try {
	        InternetGatewayDevice[] IGDs = InternetGatewayDevice.getDevices( discoveryTimeout );
	        if ( IGDs != null ) {
	          // let's the the first device found
	          testIGD = IGDs[0];
	          return true;
	          
	        }
	      } catch ( IOException ex ) {
	        ex.printStackTrace();
	      }
	      return false;
	}
	public boolean close()
	{
		try
		{
			return testIGD.deletePortMapping( null, port, "TCP" );
		}
		catch (IOException e)
		{
			
			e.printStackTrace();
		}
		catch (UPNPResponseException e)
		{
			
			e.printStackTrace();
		}
		return false;
	}
	public String publicIp()
	{
		try
		{
			return testIGD.getExternalIPAddress();
		}
		catch (Exception e)
		{
			return null;
		}
	}
    public boolean open()
    {
	
    		try
			{
				// we assume that localHostIP is something else than 127.0.0.1
				  
				  
				  
				  String localHostIP = InetAddress.getLocalHost().getHostAddress();

				  boolean mapped = testIGD.addPortMapping( "Some mapping description", 
				                                           null, 9090, 9090,
				                                           localHostIP, 0, "TCP" );
				  return mapped;
			}
			catch (Exception e)
			{
				
				e.printStackTrace();
				return false;
			}
	       
	     
    }

    public static void main(String[] args)
    {
    	UpnpUtils u = new UpnpUtils(10000);
    	if (u.find())
    	{
    		System.out.println("Found");
    		String ip = u.publicIp();
    		System.out.println("Public IP: "+ip);
    	}
    	else
    	{
    		System.out.println("Not Found");
    	}
    }
    
}